package revendication

import java.util.List;

class PostController {

    def scaffold = true
	
	List<Integer> list
	
//	def like = {
//		def post = Post.findById(params.id)
//		if(!session.postsvoted)
//		{
//	   		post.likes++
//			session.postvoted = [post.id]
//		} else {
//			list = session.postvoted
//			if(!list.contains(post.id)) {
//				post.like++
//				list.add(post.id)
//			}
//			
//		}
//		render(""+post.likes)
//	}
	
	def like = {
		// TODO : check here not very cool ?
		if(session.user) {
			def post = Post.findById(params.id)
			def user = User.findById(session.user.id)
			if(!post.likeUsers.contains(user)) {
				user.addToLikedPosts(post)
				user.save()
				render(post.likeUsers.size())
			}
			else render("vous avez deja vote pour ce Post")
			
		}
	}
	
	def comment = {
		// TODO : check here not very cool ?
		if(session.user) {
			def post = Post.findById(params.id)
			def user = User.findById(session.user.id)
			def com = new Comment(content : params.comment);
			user.addToComments(com)
			post.addToComments(com)
			user.save()
		}
		redirect(action:"more",id:params.id)
	}
	
	def more = {
		[post : Post.findById(params.id)]
	}
	
	def create = {
		def postInstance = new Post()
		postInstance.properties = params
		
		return [postInstance: postInstance, users:User.list()]
	}
	
	def newPost = {
		
		def user = User.findById(session.user.id)
		def postInstance = new Post(params)
		user.addToPosts(postInstance)
		user.save()
		
		if (postInstance.save(flush: true)) {
			flash.message = "Post created"
			redirect(controller:"user",action: "home")
		}
		else {
			render(view: "create", model: [postInstance: postInstance])
		}
	}
}
